//! 核心数据类型定义
//! 
//! 定义沙箱管理器中使用的所有核心数据结构

use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant, SystemTime};
use uuid::Uuid;
use std::collections::HashMap;

/// 沙箱唯一标识符
pub type SandboxId = Uuid;

/// 语言类型
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Language {
    Python,
    JavaScript,
    Java,
    Go,
    Rust,
    Cpp,
    #[serde(other)]
    Unknown,
}

impl std::fmt::Display for Language {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Language::Python => write!(f, "python"),
            Language::JavaScript => write!(f, "javascript"),
            Language::Java => write!(f, "java"),
            Language::Go => write!(f, "go"),
            Language::Rust => write!(f, "rust"),
            Language::Cpp => write!(f, "cpp"),
            Language::Unknown => write!(f, "unknown"),
        }
    }
}

/// 请求优先级
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Priority {
    Low,
    Normal,
    High,
    Critical,
}

impl Default for Priority {
    fn default() -> Self {
        Self::Normal
    }
}

/// 沙箱状态
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SandboxState {
    /// 正在创建
    Creating,
    /// 正在启动
    Starting,
    /// 运行中（可用于分配）
    Running,
    /// 正在执行任务
    Busy,
    /// 正在停止
    Stopping,
    /// 已停止
    Stopped,
    /// 错误状态
    Error(String),
}

/// 池类型
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PoolType {
    /// 冷池 - 存储快照模板
    Cold,
    /// 温池 - 预热但未完全初始化的沙箱
    Warm,
    /// 热池 - 完全就绪的沙箱
    Hot,
}

/// 沙箱规格配置
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SandboxSpec {
    /// CPU核心数
    pub cpu_cores: u32,
    /// 内存大小（MB）
    pub memory_mb: u64,
    /// 磁盘大小（MB）
    pub disk_mb: u64,
    /// 网络是否启用
    pub network_enabled: bool,
    /// 超时时间（秒）
    pub timeout_secs: u64,
    /// 语言环境
    pub language: Language,
    /// 环境变量
    pub env_vars: HashMap<String, String>,
    /// 快照路径（可选）
    pub snapshot_path: Option<String>,
    /// 内存文件路径（可选）
    pub memory_file_path: Option<String>,
    /// 内核镜像路径（可选）
    pub kernel_image_path: Option<String>,
    /// 根文件系统路径（可选）
    pub rootfs_path: Option<String>,
}

impl Default for SandboxSpec {
    fn default() -> Self {
        Self {
            cpu_cores: 1,
            memory_mb: 256,
            disk_mb: 1024,
            network_enabled: false,
            timeout_secs: 300,
            language: Language::Python,
            env_vars: HashMap::new(),
            snapshot_path: None,
            memory_file_path: None,
            kernel_image_path: None,
            rootfs_path: None,
        }
    }
}

/// 沙箱元数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxMetadata {
    /// 沙箱ID
    pub id: SandboxId,
    /// 沙箱规格
    pub spec: SandboxSpec,
    /// 当前状态
    pub state: SandboxState,
    /// 创建时间
    pub created_at: SystemTime,
    /// 启动时间
    pub started_at: Option<SystemTime>,
    /// 最后使用时间
    pub last_used: Option<SystemTime>,
    /// 使用次数
    pub usage_count: u64,
    /// 所属池类型
    pub pool_type: Option<PoolType>,
    /// 标签
    pub labels: HashMap<String, String>,
}

impl SandboxMetadata {
    /// 创建新的沙箱元数据
    pub fn new(spec: SandboxSpec) -> Self {
        Self {
            id: Uuid::new_v4(),
            spec,
            state: SandboxState::Creating,
            created_at: SystemTime::now(),
            started_at: None,
            last_used: None,
            usage_count: 0,
            pool_type: None,
            labels: HashMap::new(),
        }
    }
    
    /// 标记为已启动
    pub fn mark_started(&mut self) {
        self.state = SandboxState::Running;
        self.started_at = Some(SystemTime::now());
    }
    
    /// 标记为使用中
    pub fn mark_busy(&mut self) {
        self.state = SandboxState::Busy;
        self.last_used = Some(SystemTime::now());
        self.usage_count += 1;
    }
    
    /// 标记为运行中（使用完毕）
    pub fn mark_available(&mut self) {
        self.state = SandboxState::Running;
    }
    
    /// 获取运行时间
    pub fn uptime(&self) -> Option<Duration> {
        self.started_at.and_then(|started| {
            SystemTime::now().duration_since(started).ok()
        })
    }
    
    /// 获取空闲时间
    pub fn idle_time(&self) -> Option<Duration> {
        self.last_used.and_then(|last_used| {
            SystemTime::now().duration_since(last_used).ok()
        })
    }
}

/// 资源需求配置
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceRequirements {
    /// 内存大小（MB）
    pub memory_mb: u32,
    /// CPU核心数
    pub cpu_cores: u32,
    /// 磁盘大小（MB）
    pub disk_mb: u32,
    /// 网络是否启用
    pub network_enabled: bool,
    /// 网络带宽需求（Mbps）
    pub network_bandwidth_mbps: u32,
}

impl Default for ResourceRequirements {
    fn default() -> Self {
        Self {
            memory_mb: 512,
            cpu_cores: 1,
            disk_mb: 1024,
            network_enabled: true,
            network_bandwidth_mbps: 100,
        }
    }
}

/// 依赖项
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Dependency {
    /// 依赖名称
    pub name: String,
    /// 版本
    pub version: String,
    /// 来源
    pub source: String,
}

/// 代码执行请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionRequest {
    /// 沙箱ID
    pub sandbox_id: SandboxId,
    /// 要执行的源代码
    pub source_code: String,
    /// 编程语言
    pub language: Language,
    /// 入口点
    pub entry_point: String,
    /// 依赖项列表
    pub dependencies: Vec<Dependency>,
    /// 环境变量
    pub env_vars: HashMap<String, String>,
    /// 标准输入
    pub stdin: String,
    /// 超时时间（毫秒）
    pub timeout_ms: Option<u64>,
}

/// 代码执行结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionResult {
    /// 执行是否成功
    pub success: bool,
    /// 标准输出
    pub stdout: String,
    /// 标准错误输出
    pub stderr: String,
    /// 退出码
    pub exit_code: Option<i32>,
    /// 执行时间（毫秒）
    pub execution_time_ms: u64,
    /// 内存使用峰值（MB）
    pub memory_usage_mb: u64,
}

/// 资源使用统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceUsage {
    /// CPU使用率（百分比）
    pub cpu_percent: f64,
    /// 内存使用量（MB）
    pub memory_mb: u64,
    /// 磁盘使用量（MB）
    pub disk_mb: u64,
    /// 网络接收字节数
    pub network_rx_bytes: u64,
    /// 网络发送字节数
    pub network_tx_bytes: u64,
    /// 采集时间
    pub timestamp: SystemTime,
}

/// 健康检查结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthStatus {
    /// 是否健康
    pub healthy: bool,
    /// 检查时间
    pub checked_at: SystemTime,
    /// 响应时间（毫秒）
    pub response_time_ms: u64,
    /// 错误信息
    pub error_message: Option<String>,
    /// 详细信息
    pub details: HashMap<String, String>,
}

/// 调度策略
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SchedulingStrategy {
    /// 轮询
    RoundRobin,
    /// 最少使用
    LeastUsed,
    /// 最少连接
    LeastConnections,
    /// 加权轮询
    WeightedRoundRobin(Vec<u32>),
    /// 自适应
    Adaptive,
}

/// 调度请求
#[derive(Debug, Clone)]
pub struct SchedulingRequest {
    /// 语言要求
    pub language: Language,
    /// 资源规格要求
    pub spec: SandboxSpec,
    /// 优先级
    pub priority: Priority,
    /// 请求时间
    pub requested_at: Instant,
    /// 超时时间
    pub timeout: Duration,
}

/// 调度结果
#[derive(Debug, Clone)]
pub struct SchedulingResult {
    /// 分配的沙箱ID
    pub sandbox_id: Option<SandboxId>,
    /// 分配延迟（毫秒）
    pub allocation_latency_ms: u64,
    /// 是否来自缓存
    pub from_cache: bool,
    /// 来源池类型
    pub source_pool: Option<PoolType>,
}

/// 池统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PoolStats {
    /// 池类型
    pub pool_type: PoolType,
    /// 总容量
    pub total_capacity: usize,
    /// 已使用数量
    pub used_count: usize,
    /// 空闲数量
    pub idle_count: usize,
    /// 创建中数量
    pub creating_count: usize,
    /// 错误数量
    pub error_count: usize,
    /// 平均分配延迟（毫秒）
    pub avg_allocation_latency_ms: f64,
    /// 缓存命中率（百分比）
    pub cache_hit_rate: f64,
}

impl PoolStats {
    /// 计算使用率
    pub fn utilization(&self) -> f64 {
        if self.total_capacity == 0 {
            0.0
        } else {
            (self.used_count as f64) / (self.total_capacity as f64) * 100.0
        }
    }
    
    /// 计算可用率
    pub fn availability(&self) -> f64 {
        if self.total_capacity == 0 {
            0.0
        } else {
            (self.idle_count as f64) / (self.total_capacity as f64) * 100.0
        }
    }
}

/// 系统整体统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemStats {
    /// 总沙箱数量
    pub total_sandboxes: usize,
    /// 活跃沙箱数量
    pub active_sandboxes: usize,
    /// 各池统计信息
    pub pool_stats: HashMap<PoolType, PoolStats>,
    /// 各语言沙箱分布
    pub language_distribution: HashMap<Language, usize>,
    /// 系统负载
    pub system_load: f64,
    /// 内存使用率
    pub memory_usage_percent: f64,
    /// 统计时间
    pub timestamp: SystemTime,
}

/// 资源限制配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLimits {
    /// 最大CPU使用百分比
    pub max_cpu_percentage: f64,
    /// 最大内存使用量(MB)
    pub max_memory_mb: u32,
    /// 最大磁盘读取次数/秒
    pub max_disk_reads_per_sec: u64,
    /// 最大磁盘写入次数/秒
    pub max_disk_writes_per_sec: u64,
    /// 最大网络带宽(Kbps)
    pub max_network_bandwidth_kbps: u64,
}

impl Default for ResourceLimits {
    fn default() -> Self {
        Self {
            max_cpu_percentage: 80.0,
            max_memory_mb: 1024,
            max_disk_reads_per_sec: 1000,
            max_disk_writes_per_sec: 1000,
            max_network_bandwidth_kbps: 1000,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::time::SystemTime;
    
    #[test]
    fn test_language_display() {
        assert_eq!(Language::Python.to_string(), "python");
        assert_eq!(Language::JavaScript.to_string(), "javascript");
        assert_eq!(Language::Java.to_string(), "java");
        assert_eq!(Language::Go.to_string(), "go");
        assert_eq!(Language::Rust.to_string(), "rust");
        assert_eq!(Language::Cpp.to_string(), "cpp");
        assert_eq!(Language::Unknown.to_string(), "unknown");
    }

    #[test]
    fn test_language_equality() {
        assert_eq!(Language::Python, Language::Python);
        assert_ne!(Language::Python, Language::JavaScript);
        assert_ne!(Language::Unknown, Language::Python);
    }

    #[test]
    fn test_priority_ordering() {
        assert!(Priority::Low < Priority::Normal);
        assert!(Priority::Normal < Priority::High);
        assert!(Priority::High < Priority::Critical);
        
        let mut priorities = vec![Priority::High, Priority::Low, Priority::Critical, Priority::Normal];
        priorities.sort();
        assert_eq!(priorities, vec![Priority::Low, Priority::Normal, Priority::High, Priority::Critical]);
    }

    #[test]
    fn test_priority_default() {
        assert_eq!(Priority::default(), Priority::Normal);
    }

    #[test]
    fn test_sandbox_state_variants() {
        let states = vec![
            SandboxState::Creating,
            SandboxState::Starting,
            SandboxState::Running,
            SandboxState::Busy,
            SandboxState::Stopping,
            SandboxState::Stopped,
            SandboxState::Error("Test error".to_string()),
        ];
        
        for state in states {
            match state {
                SandboxState::Error(ref msg) => assert_eq!(msg, "Test error"),
                _ => {} // 其他状态都正常
            }
        }
    }

    #[test]
    fn test_pool_type_variants() {
        let pool_types = vec![PoolType::Cold, PoolType::Warm, PoolType::Hot];
        
        for pool_type in pool_types {
            assert!(matches!(pool_type, PoolType::Cold | PoolType::Warm | PoolType::Hot));
        }
    }

    #[test]
    fn test_sandbox_spec_creation() {
        let spec = SandboxSpec {
            cpu_cores: 2,
            memory_mb: 1024,
            disk_mb: 2048,
            network_enabled: true,
            timeout_secs: 300,
            language: Language::Python,
            environment_variables: HashMap::new(),
            startup_command: vec!["python".to_string()],
            working_directory: "/tmp".to_string(),
            resource_limits: ResourceLimits {
                max_cpu_percentage: 80.0,
                max_memory_mb: 1024,
                max_disk_reads_per_sec: 1000,
                max_disk_writes_per_sec: 1000,
                max_network_bandwidth_kbps: 1000,
            },
        };
        
        assert_eq!(spec.cpu_cores, 2);
        assert_eq!(spec.memory_mb, 1024);
        assert_eq!(spec.language, Language::Python);
        assert!(spec.network_enabled);
        assert_eq!(spec.resource_limits.max_cpu_percentage, 80.0);
    }

    #[test]
    fn test_sandbox_spec_default() {
        let spec = SandboxSpec::default();
        
        assert!(spec.cpu_cores > 0);
        assert!(spec.memory_mb > 0);
        assert!(spec.timeout_secs > 0);
        assert!(!spec.startup_command.is_empty());
    }

    #[test]
    fn test_resource_limits() {
        let limits = ResourceLimits {
            max_cpu_percentage: 90.0,
            max_memory_mb: 2048,
            max_disk_reads_per_sec: 5000,
            max_disk_writes_per_sec: 3000,
            max_network_bandwidth_kbps: 10000,
        };
        
        assert_eq!(limits.max_cpu_percentage, 90.0);
        assert_eq!(limits.max_memory_mb, 2048);
        assert_eq!(limits.max_disk_reads_per_sec, 5000);
        assert_eq!(limits.max_disk_writes_per_sec, 3000);
        assert_eq!(limits.max_network_bandwidth_kbps, 10000);
    }

    #[test]
    fn test_resource_limits_default() {
        let limits = ResourceLimits::default();
        
        assert!(limits.max_cpu_percentage > 0.0);
        assert!(limits.max_cpu_percentage <= 100.0);
        assert!(limits.max_memory_mb > 0);
    }

    #[test]
    fn test_sandbox_metadata_creation() {
        let spec = SandboxSpec::default();
        let metadata = SandboxMetadata::new(spec.clone());
        
        assert_eq!(metadata.spec, spec);
        assert_eq!(metadata.state, SandboxState::Creating);
        assert_eq!(metadata.usage_count, 0);
        assert!(metadata.started_at.is_none());
        assert!(metadata.last_used.is_none());
        assert!(metadata.created_at <= SystemTime::now());
    }

    #[test]
    fn test_sandbox_metadata_lifecycle() {
        let spec = SandboxSpec::default();
        let mut metadata = SandboxMetadata::new(spec);
        
        // 测试启动
        metadata.mark_started();
        assert_eq!(metadata.state, SandboxState::Running);
        assert!(metadata.started_at.is_some());
        
        // 测试标记为忙碌
        metadata.mark_busy();
        assert_eq!(metadata.state, SandboxState::Busy);
        assert_eq!(metadata.usage_count, 1);
        assert!(metadata.last_used.is_some());
        
        // 测试释放
        metadata.mark_available();
        assert_eq!(metadata.state, SandboxState::Running);
        
        // 测试停止
        metadata.mark_stopped();
        assert_eq!(metadata.state, SandboxState::Stopped);
        
        // 测试错误
        metadata.mark_error("Test error".to_string());
        match metadata.state {
            SandboxState::Error(ref msg) => assert_eq!(msg, "Test error"),
            _ => panic!("应该是错误状态"),
        }
    }

    #[test]
    fn test_sandbox_metadata_uptime() {
        let spec = SandboxSpec::default();
        let mut metadata = SandboxMetadata::new(spec);
        
        // 未启动时应该返回None
        assert!(metadata.uptime().is_none());
        
        // 启动后应该有运行时间
        metadata.mark_started();
        let uptime = metadata.uptime();
        assert!(uptime.is_some());
        assert!(uptime.unwrap().as_millis() >= 0);
    }

    #[test]
    fn test_sandbox_metadata_multiple_usage() {
        let spec = SandboxSpec::default();
        let mut metadata = SandboxMetadata::new(spec);
        
        metadata.mark_started();
        
        // 多次使用
        for i in 1..=5 {
            metadata.mark_busy();
            assert_eq!(metadata.usage_count, i);
            metadata.mark_available();
        }
        
        assert_eq!(metadata.usage_count, 5);
    }

    #[test]
    fn test_execution_request_creation() {
        let mut env_vars = HashMap::new();
        env_vars.insert("PYTHONPATH".to_string(), "/usr/lib/python3".to_string());
        
        let request = ExecutionRequest {
            code: "print('hello world')".to_string(),
            language: Language::Python,
            timeout_ms: Some(5000),
            env_vars,
            working_dir: Some("/tmp".to_string()),
            stdin: Some("input data".to_string()),
        };
        
        assert_eq!(request.code, "print('hello world')");
        assert_eq!(request.language, Language::Python);
        assert_eq!(request.timeout_ms, Some(5000));
        assert_eq!(request.working_dir, Some("/tmp".to_string()));
        assert_eq!(request.stdin, Some("input data".to_string()));
        assert_eq!(request.env_vars.get("PYTHONPATH").unwrap(), "/usr/lib/python3");
    }

    #[test]
    fn test_execution_request_default_timeout() {
        let request = ExecutionRequest {
            code: "console.log('hello')".to_string(),
            language: Language::JavaScript,
            timeout_ms: None, // 使用默认超时
            env_vars: HashMap::new(),
            working_dir: None,
            stdin: None,
        };
        
        assert!(request.timeout_ms.is_none());
        assert_eq!(request.language, Language::JavaScript);
    }

    #[test]
    fn test_execution_result_success() {
        let result = ExecutionResult {
            success: true,
            stdout: "Hello, World!".to_string(),
            stderr: "".to_string(),
            exit_code: 0,
            execution_time_ms: 150,
            memory_used_kb: 1024,
        };
        
        assert!(result.success);
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "Hello, World!");
        assert!(result.stderr.is_empty());
        assert_eq!(result.execution_time_ms, 150);
        assert_eq!(result.memory_used_kb, 1024);
    }

    #[test]
    fn test_execution_result_failure() {
        let result = ExecutionResult {
            success: false,
            stdout: "".to_string(),
            stderr: "SyntaxError: invalid syntax".to_string(),
            exit_code: 1,
            execution_time_ms: 50,
            memory_used_kb: 512,
        };
        
        assert!(!result.success);
        assert_ne!(result.exit_code, 0);
        assert!(result.stdout.is_empty());
        assert!(!result.stderr.is_empty());
    }

    #[test]
    fn test_pool_stats_creation() {
        let stats = PoolStats {
            pool_type: PoolType::Hot,
            total_capacity: 100,
            used_count: 30,
            idle_count: 50,
            creating_count: 15,
            error_count: 5,
            successful_acquisitions: 1000,
            failed_acquisitions: 50,
            avg_response_time_ms: 25.5,
            success_rate: 95.2,
            last_updated: SystemTime::now(),
        };
        
        assert_eq!(stats.pool_type, PoolType::Hot);
        assert_eq!(stats.total_capacity, 100);
        assert_eq!(stats.used_count, 30);
        assert_eq!(stats.idle_count, 50);
        assert_eq!(stats.creating_count, 15);
        assert_eq!(stats.error_count, 5);
        assert_eq!(stats.successful_acquisitions, 1000);
        assert_eq!(stats.failed_acquisitions, 50);
        assert_eq!(stats.avg_response_time_ms, 25.5);
        assert_eq!(stats.success_rate, 95.2);
    }

    #[test]
    fn test_pool_stats_calculations() {
        let stats = PoolStats {
            pool_type: PoolType::Warm,
            total_capacity: 200,
            used_count: 60,
            idle_count: 100,
            creating_count: 30,
            error_count: 10,
            successful_acquisitions: 500,
            failed_acquisitions: 25,
            avg_response_time_ms: 45.0,
            success_rate: 95.2,
            last_updated: SystemTime::now(),
        };
        
        // 利用率 = 使用中 / 总容量
        assert_eq!(stats.utilization(), 30.0); // 60/200 * 100%
        
        // 可用率 = 空闲 / 总容量
        assert_eq!(stats.availability(), 50.0); // 100/200 * 100%
        
        // 错误率 = 错误 / 总容量
        assert_eq!(stats.error_rate(), 5.0); // 10/200 * 100%
    }

    #[test]
    fn test_pool_stats_edge_cases() {
        // 空池
        let empty_stats = PoolStats {
            pool_type: PoolType::Cold,
            total_capacity: 0,
            used_count: 0,
            idle_count: 0,
            creating_count: 0,
            error_count: 0,
            successful_acquisitions: 0,
            failed_acquisitions: 0,
            avg_response_time_ms: 0.0,
            success_rate: 0.0,
            last_updated: SystemTime::now(),
        };
        
        assert_eq!(empty_stats.utilization(), 0.0);
        assert_eq!(empty_stats.availability(), 0.0);
        assert_eq!(empty_stats.error_rate(), 0.0);
        
        // 满容量
        let full_stats = PoolStats {
            pool_type: PoolType::Hot,
            total_capacity: 50,
            used_count: 50,
            idle_count: 0,
            creating_count: 0,
            error_count: 0,
            successful_acquisitions: 200,
            failed_acquisitions: 0,
            avg_response_time_ms: 10.0,
            success_rate: 100.0,
            last_updated: SystemTime::now(),
        };
        
        assert_eq!(full_stats.utilization(), 100.0);
        assert_eq!(full_stats.availability(), 0.0);
        assert_eq!(full_stats.error_rate(), 0.0);
    }

    #[test]
    fn test_system_stats_creation() {
        let mut pool_stats = HashMap::new();
        pool_stats.insert(PoolType::Hot, PoolStats {
            pool_type: PoolType::Hot,
            total_capacity: 50,
            used_count: 20,
            idle_count: 25,
            creating_count: 5,
            error_count: 0,
            successful_acquisitions: 100,
            failed_acquisitions: 5,
            avg_response_time_ms: 15.0,
            success_rate: 95.2,
            last_updated: SystemTime::now(),
        });
        
        let mut language_distribution = HashMap::new();
        language_distribution.insert(Language::Python, 15);
        language_distribution.insert(Language::JavaScript, 10);
        
        let system_stats = SystemStats {
            total_sandboxes: 50,
            active_sandboxes: 45,
            pool_stats,
            language_distribution,
            system_load: 0.65,
            memory_usage_percent: 72.5,
            timestamp: SystemTime::now(),
        };
        
        assert_eq!(system_stats.total_sandboxes, 50);
        assert_eq!(system_stats.active_sandboxes, 45);
        assert_eq!(system_stats.system_load, 0.65);
        assert_eq!(system_stats.memory_usage_percent, 72.5);
        assert_eq!(system_stats.pool_stats.len(), 1);
        assert_eq!(system_stats.language_distribution.len(), 2);
        assert_eq!(system_stats.language_distribution.get(&Language::Python).unwrap(), &15);
    }

    #[test]
    fn test_resource_requirements_creation() {
        let requirements = ResourceRequirements {
            memory_mb: 1024,
            cpu_cores: 2,
            disk_mb: 2048,
            network_bandwidth_mbps: 100,
        };
        
        assert_eq!(requirements.memory_mb, 1024);
        assert_eq!(requirements.cpu_cores, 2);
        assert_eq!(requirements.disk_mb, 2048);
        assert_eq!(requirements.network_bandwidth_mbps, 100);
    }

    #[test]
    fn test_resource_requirements_default() {
        let requirements = ResourceRequirements::default();
        
        assert!(requirements.memory_mb > 0);
        assert!(requirements.cpu_cores > 0);
        assert!(requirements.disk_mb > 0);
        assert!(requirements.network_bandwidth_mbps > 0);
    }

    #[test]
    fn test_serialization_deserialization() {
        let original_language = Language::Python;
        let serialized = serde_json::to_string(&original_language).unwrap();
        let deserialized: Language = serde_json::from_str(&serialized).unwrap();
        assert_eq!(original_language, deserialized);
        
        let original_priority = Priority::High;
        let serialized = serde_json::to_string(&original_priority).unwrap();
        let deserialized: Priority = serde_json::from_str(&serialized).unwrap();
        assert_eq!(original_priority, deserialized);
        
        let original_pool_type = PoolType::Warm;
        let serialized = serde_json::to_string(&original_pool_type).unwrap();
        let deserialized: PoolType = serde_json::from_str(&serialized).unwrap();
        assert_eq!(original_pool_type, deserialized);
    }

    #[test]
    fn test_language_hash() {
        use std::collections::HashSet;
        
        let mut languages = HashSet::new();
        languages.insert(Language::Python);
        languages.insert(Language::JavaScript);
        languages.insert(Language::Python); // 重复插入
        
        assert_eq!(languages.len(), 2); // 去重后只有2个
        assert!(languages.contains(&Language::Python));
        assert!(languages.contains(&Language::JavaScript));
    }

    #[test]
    fn test_priority_hash() {
        use std::collections::HashSet;
        
        let mut priorities = HashSet::new();
        priorities.insert(Priority::Low);
        priorities.insert(Priority::High);
        priorities.insert(Priority::Low); // 重复插入
        
        assert_eq!(priorities.len(), 2);
        assert!(priorities.contains(&Priority::Low));
        assert!(priorities.contains(&Priority::High));
    }

    #[test]
    fn test_pool_type_hash() {
        use std::collections::HashMap;
        
        let mut pool_map = HashMap::new();
        pool_map.insert(PoolType::Hot, "hot_pool");
        pool_map.insert(PoolType::Warm, "warm_pool");
        pool_map.insert(PoolType::Cold, "cold_pool");
        
        assert_eq!(pool_map.len(), 3);
        assert_eq!(pool_map.get(&PoolType::Hot).unwrap(), &"hot_pool");
        assert_eq!(pool_map.get(&PoolType::Warm).unwrap(), &"warm_pool");
        assert_eq!(pool_map.get(&PoolType::Cold).unwrap(), &"cold_pool");
    }

    #[test]
    fn test_clone_implementations() {
        let original_language = Language::Python;
        let cloned_language = original_language.clone();
        assert_eq!(original_language, cloned_language);
        
        let original_state = SandboxState::Running;
        let cloned_state = original_state.clone();
        assert_eq!(original_state, cloned_state);
        
        let original_spec = SandboxSpec::default();
        let cloned_spec = original_spec.clone();
        assert_eq!(original_spec, cloned_spec);
    }
}